<template>
  <div class="page-main"  v-title :data-title="dataTitle?dataTitle:'质量通知单列表'">
    <home-nav :userData="userinfo"></home-nav>
    <div class="banner"><span>质量通知单</span></div>
    <div class="container">
      <div class="header">
        <a-row type="flex" justify="space-between" align="middle">
          <a-col :xl="{ span: 14 }" :lg="{ span: 11 }">
            <a-button class="hte-btn add-btn" type="primary" icon="plus" @click="toAdd()">创建</a-button>

            <a-button class="hte-btn del-btn" @click="toEdit()">编辑</a-button>
            <a-button class="hte-btn del-btn" @click="showSearchForm = true">查询</a-button>
            <a-button class="hte-btn port-btn" @click="exportExcle">导出</a-button>
            <a-button @click="fetchQualityList" class="hte-btn">刷新</a-button>
            <a-radio-group v-model="platForm" @change="changePlatForm">
              <a-radio-button value="1"> 海芯 </a-radio-button>
              <a-radio-button value="2"> 海澜 </a-radio-button>
            </a-radio-group>
          </a-col>
          <a-col :xl="{ span: 9 }" :lg="{ span: 13 }" class="input-ground">
            <a-input-group compact>
              <a-select v-model="keywordType" @change="changeKeywordType">
                <a-select-option value="1"> 单据名称 </a-select-option>
                <a-select-option value="2"> 通知单号 </a-select-option>
              </a-select>
              <a-input-search
                v-if="keywordType == '1'"
                v-model="searchForm.name"
                @search="handleSearch"
                placeholder="请按照关键字进行搜索"
              />
              <a-input-search
                v-if="keywordType == '2'"
                v-model="searchForm.qualityNo"
                @search="handleSearch"
                placeholder="请按照关键字进行搜索"
              />
            </a-input-group>
            <!-- <a-button class="hte-btn del-btn" @click="showSearchForm = true">高级搜索</a-button> -->
          </a-col>
        </a-row>
      </div>
      <div class="floatNav">
        <!-- <div class="budget-detail" @click="toMyTask">
          <span class="iconfont icon-reportReserve"></span>
          <a-badge :offset="[-11, -15]">
            <p>我的报工单</p>
          </a-badge>
        </div> -->
        <!-- <div class="budget-detail">
          <span class="iconfont icon-reportReserve"></span>
          <a-badge count="22" :offset="[-11, -15]">
            <p>验收付款单</p>
          </a-badge>
        </div> -->
      </div>
      <div class="content-list">
        <a-table
          :scroll="{ x: 1800 }"
          :columns="[...qualityColumns, ...deleteColums]"
          :data-source="qualityRecords"
          rowKey="id"
          bordered
          :pagination="false"
          @change="qualityHandleTableChange"
          :customRow="customQualityRow"
        >
          <span slot="qualityNoRender" slot-scope="text, record">
            <span class="font-active" @click="toQualityDetail(record)">
              {{ record.qualityNo }}
            </span>
          </span>
          <template slot="handlerStepRender" slot-scope="text, record">
            {{ record.handlerStep }}
          </template>
          <template slot="statusRender" slot-scope="text, record, index">
            <div v-if="record.platForm == '海芯'">
              <a-select
                :disabled="!checkPermission(['WORK_REPORT_ADMIN']) && !(userinfo.info.username == 'panlj')"
                v-model="record.status"
                style="width: 100%"
                :allowClear="true"
                @change="changeSave(index)"
              >
                <a-select-option v-for="(code, index) in codes.WorkReportQualityStatus" :key="index" :value="code.code">
                  {{ code.name }}
                </a-select-option>
              </a-select>
            </div>
            <div v-else>
              <a-select disabled :value="record.status + ''" style="width: 100%" :allowClear="true">
                <a-select-option v-for="(code, index) in codes.WorkReportQualityStatus" :key="index" :value="code.code">
                  {{ code.name }}
                </a-select-option>
              </a-select>
            </div>
          </template>
          <template slot="qualityTypeRender" slot-scope="text, record">
            <template v-for="item in codes.QualityType">
              <template v-if="record.qualityType ? record.qualityType.indexOf(item.code) > -1 : false">
                {{ item.name }}
              </template>
            </template>
          </template>
          <template slot="billTypeRender" slot-scope="text, record">
            <template v-for="item in codes.QualityBillType">
              <template v-if="item.code == record.billType">
                {{ item.name }}
              </template>
            </template>
          </template>
          <template slot="supplierRender" slot-scope="text, record">
            {{ record.supplierName + '/' + record.supplierCode }}
          </template>
          <template slot="currentHandlerRender" slot-scope="text, record">
            {{ currentHandlerRenderFunc(record) }}
          </template>
          <span slot="actionRender" slot-scope="text, record">
            <span v-if="record.platForm == '海芯'" class="font-active" @click="toDelQuality(record)"> 删除 </span>
            <span v-else class="font-active"> </span>
          </span>
        </a-table>
        <a-pagination
          v-if="qualityRecords.length > 0"
          style="padding: 15px 30px"
          v-model="searchForm.current"
          :page-size-options="pageSizeOptions"
          :total="searchForm.total"
          show-size-changer
          :page-size="searchForm.pageSize"
          @change="pageChange"
          @showSizeChange="onShowSizeChange"
          :show-total="(total) => `共 ${total} 条`"
        >
          <template slot="buildOptionText" slot-scope="props">
            <span v-if="props.value !== '50'">{{ props.value }}条/页</span>
            <span v-if="props.value === '50'">全部</span>
          </template>
        </a-pagination>
      </div>
    </div>
    <a-modal
      :visible="showSearchForm"
      width="70vw"
      :bodyStyle="{ padding: '10px' }"
      title="高级查询"
      @ok="handleToSearch"
      @cancel="handleToCancel"
    >
      <a-form-model ref="ruleForm" :label-col="labelCol" :wrapper-col="wrapperCol">
        <a-row :gutter="24">
          <a-col :span="8">
            <a-form-model-item label="单据状态">
              <a-select v-model="searchForm.status" style="width: 100%" :allowClear="true">
                <a-select-option v-for="(code, index) in codes.WorkReportQualityStatus" :key="index" :value="code.code">
                  {{ code.name }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="质量通知单号">
              <a-input v-model="searchForm.qualityNo" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="单据名称">
              <a-input v-model="searchForm.name" />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :span="8">
            <a-form-model-item label="合同编号">
              <a-input v-model="searchForm.createOrderUser" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="采购订单号">
              <a-input v-model="searchForm.poNo" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="供应商">
              <a-input v-model="searchForm.supplierName" />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :span="8">
            <a-form-model-item label="申请人">
              <a-input v-model="searchForm.applyUser" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="单据类型">
              <a-select v-model="searchForm.billType">
                <a-select-option
                  v-for="(item, index) in codes.QualityBillType"
                  :key="'type' + index"
                  :value="item.code"
                >
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="违约类型">
              <a-select v-model="searchForm.qualityType">
                <a-select-option v-for="(item, index) in codes.QualityType" :key="'type' + index" :value="item.code">
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :span="16">
            <a-form-model-item label="采购管理分工时间">
              <div style="display: flex">
                <a-date-picker
                  style="width: 120px"
                  valueFormat="YYYY-MM-DD"
                  placeholder="开始时间"
                  v-model="searchForm.followHeaderAuditTimeStart"
                />
                <div style="line-height:36px;padding0px 3px">至</div>
                <a-date-picker
                  style="width: 120px"
                  valueFormat="YYYY-MM-DD"
                  placeholder="结束时间"
                  v-model="searchForm.followHeaderAuditTimeEnd"
                />
              </div>
            </a-form-model-item>
          </a-col>
          <a-col :span="8"> </a-col>
        </a-row>
      </a-form-model>
    </a-modal>
  </div>
</template>
<script>
import { getAction, postAction } from '@/api/manage'
import { UtilsMixin } from '@/mixins/UtilsMixin'
import { Modal } from 'ant-design-vue'
export default {
  mixins: [UtilsMixin],
  components: {
    HomeNav: () => import('@/components/layouts/HomeNav'),
  },
  props: {
    show: {
      type: Boolean,
      default: false,
    },
    poNo: {
      type: String,
      default: null,
    },
  },
  computed: {
    loadList() {
      return this.show
    },
  },
  data() {
    return {
      dataTitle:this.$route?this.$route.name:"",
      userinfo: {
        info: this.$store.getters.userInfo,
        module: 'ContractTaskList',
      },
      labelCol: { span: 8 },
      wrapperCol: { span: 15 },
      deleteColums: [
        {
          title: '操作',
          width: '100px',
          align: 'center',
          scopedSlots: { customRender: 'actionRender' },
          ellipsis: true,
        },
      ],
      qualityColumns: [
        {
          title: '单据状态',
          dataIndex: 'status',
          scopedSlots: { customRender: 'statusRender' },
          width: '150px',
          align: 'center',
          ellipsis: true,
        },
        {
          title: '当前步骤',
          dataIndex: 'handlerStep',
          scopedSlots: { customRender: 'handlerStepRender' },
          width: '100px',
          align: 'left',
          ellipsis: true,
        },
        {
          title: '当前处理人/接收时间/停留时间',
          dataIndex: 'handlerUser',
          scopedSlots: { customRender: 'currentHandlerRender' },
          width: '230px',
          align: 'center',
          ellipsis: true,
        },
        {
          title: '质量通知单号',
          dataIndex: 'qualityNo',
          width: '180px',
          align: 'left',
          scopedSlots: { customRender: 'qualityNoRender' },
          ellipsis: true,
        },
        {
          title: '质量单据名称',
          dataIndex: 'name',
          width: '200px',
          align: 'left',
          ellipsis: true,
        },
        {
          title: '单据类型',
          dataIndex: 'billType',
          width: '150px',
          align: 'left',
          scopedSlots: { customRender: 'billTypeRender' },
          ellipsis: true,
        },
        {
          title: '违约/扣罚类型',
          dataIndex: 'qualityType',
          width: '200px',
          align: 'left',
          scopedSlots: { customRender: 'qualityTypeRender' },
          ellipsis: true,
        },
        {
          title: '申报扣罚金额',
          dataIndex: 'fineAmount',
          width: '150px',
          align: 'center',
          ellipsis: true,
        },
        {
          title: '审批扣罚金额',
          dataIndex: 'spFineAmount',
          width: '150px',
          align: 'center',
          ellipsis: true,
        },
        {
          title: '采购订单号',
          dataIndex: 'poNo',
          width: '150px',
          align: 'center',
          ellipsis: true,
        },
        {
          title: '合同名称',
          dataIndex: 'contractName',
          width: '200px',
          align: 'left',
          ellipsis: true,
        },
        {
          title: '供应商名称/编码',
          dataIndex: 'supplierName',
          width: '150px',
          align: 'center',
          scopedSlots: { customRender: 'supplierRender' },
          ellipsis: true,
        },
        {
          title: '申请人',
          dataIndex: 'applyUser',
          width: '80px',
          align: 'center',
          ellipsis: true,
        },
        {
          title: '申请日期',
          dataIndex: 'applyDate',
          width: '180px',
          align: 'center',
          ellipsis: true,
        },
        {
          title: '采购管理分工时间',
          dataIndex: 'followHeaderAuditTime',
          width: '200px',
          align: 'center',
          ellipsis: true,
        },
        {
          title: '来源',
          dataIndex: 'platForm',
          width: '100px',
          align: 'center',
          ellipsis: true,
        },
      ],
      billTypeOptions: [
        { value: 1, label: '扣罚类(含非扣罚的质量问题)' },
        { value: 2, label: '非扣罚类' },
      ],
      platForm: [
        { value: 1, label: '海芯' },
        { value: 2, label: '海澜' },
      ],
      urls: {
        psQualityList: '/hte/contract/qualityList',
        psQualityList: '/hte/contract/qualityList',
        hteQualityList: '/workReport/quality/page',
        updateQuality: '/workReport/quality/updateQuality',
        delQuality: '/workReport/quality/delete',
        myPermission: '/workReport/project/myPermission',
        codes: '/manage/codeInfo/queryByTypes',
      },

      qualityModel: false,
      pageSizeOptions: ['10', '20', '30', '40', '50'],
      searchForm: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        total: 0,
        poNo: this.$route.params && this.$route.params.poNo,
      },
      qualityRecords: [],
      psQualityRecords: [],
      hteQualityRecords: [],
      permission: [],
      keywordType: '1',
      showSearchForm: false,
      codes: {},
      currentRecord: {},
      platForm: '1',
    }
  },
  mounted() {
    this.fetchCodes()
    this.fetchQualityList()
    this.fetchPermission()
  },
  methods: {
    fetchPermission() {
      getAction(this.urls.myPermission, {}).then((res) => {
        if (res.success) {
          this.permission = res.result
        }
      })
    },
    checkPermission(powers) {
      let hasPower = false
      for (let p of powers) {
        if (this.permission.indexOf(p) > -1) {
          hasPower = true
          break
        }
      }
      return hasPower
    },
    fetchCodes() {
      getAction(this.urls.codes, {
        types: 'WorkReportQualityStatus,QualityType,QualityBillType,WorkReportTaskStatus',
      }).then((res) => {
        if (res.success) {
          this.codes = { ...this.codes, ...res.result }
        }
      })
    },
    changeKeywordType() {
      if (this.keywordType == '1') {
        this.$set(this.searchForm, 'qualityNo', '')
      } else {
        this.$set(this.searchForm, 'name', '')
      }
    },
    handleSearch() {
      this.$set(this.searchForm, 'current', 1)
      this.$set(this.searchForm, 'pageNo', 1)
      this.fetchQualityList()
    },
    handleSearch() {
      this.$set(this.searchForm, 'current', 1)
      this.$set(this.searchForm, 'pageNo', 1)
      this.fetchQualityList()
    },
    changePlatForm() {
      this.$set(this.searchForm, 'current', 1)
      this.$set(this.searchForm, 'pageNo', 1)
      this.fetchQualityList()
    },
    fetchPermission() {
      getAction(this.urls.myPermission, {}).then((res) => {
        if (res.success) {
          this.permission = res.result
        }
      })
    },
    checkPermission(powers) {
      let hasPower = false
      for (let p of powers) {
        if (this.permission.indexOf(p) > -1) {
          hasPower = true
          break
        }
      }
      return hasPower
    },
    customQualityRow(record) {
      let that = this
      return {
        on: {
          dblclick: (event) => {
            this.toQualityDetail(record)
          },
          click(event) {
            that.currentRecord = record
          },
        },
      }
    },
    toQualityDetail(record) {
      if (record.platForm == '海澜') {
        let urlJump = this.$router.resolve({ path:'/workReport/quality/view/' + record.id + '/' + this.taskId })
        window.open(urlJump.href, '_blank')
      } else {
        let urlJump = this.$router.resolve({ path:'/workReport/editQuality/' + record.id })
        window.open(urlJump.href, '_blank')
      }
    },
    fetchQualityList() {
      this.qualityRecords = []
      this.psQualityRecords = []
      this.hteQualityRecords = []
      this.records = {}
      if (this.platForm == '2') {
        this.fetchPsQualityList()
      }
      if (this.platForm == '1') {
        this.fetchHteQualityList()
      }
    },
    fetchPsQualityList() {
      // if (this.searchForm.current == 0 || this.searchForm.current == 1) {
      let param = Object.assign({}, this.searchForm)
      param.pageNo = this.searchForm.current
      postAction(this.urls.psQualityList, param).then((res) => {
        if (res.success) {
          this.psQualityRecords = res.result.records
          this.psQualityRecords.forEach((r) => {
            r.platForm = '海澜'
          })
          this.$set(this.searchForm, 'total', res.result.total)
          this.qualityRecords = this.psQualityRecords
        }
      })
      // } else {
      //   this.psQualityRecords = []
      // }
    },
    fetchHteQualityList() {
      let param = Object.assign({}, this.searchForm)
      param.pageNo = this.searchForm.current
      postAction(this.urls.hteQualityList, param).then((res) => {
        if (res.success) {
          this.hteQualityRecords = res.result.records
          this.hteQualityRecords.forEach((r) => {
            r.platForm = '海芯'
          })
          this.$set(this.searchForm, 'total', res.result.total)
          this.qualityRecords = this.hteQualityRecords
        }
        this.showSearchForm = false
      })
    },
    /**
     * 表结构切换页码
     */
    qualityHandleTableChange(searchForm, filters, sorter) {
      this.searchForm = searchForm
      this.searchForm.pageNo = this.searchForm.current
      this.fetchQualityList()
    },
    currentHandlerRenderFunc(record) {
      let text = ''
      if (record.handlerUser) {
        if (record.handlerTime) {
          text = record.handlerUser + '/' + record.handlerTime + '/' + record.stayDays + '天'
          // var startDate = new Date(record.handlerTime).getTime()
          // var endDate = new Date().getTime()
          // var days = (endDate - startDate) / (1 * 24 * 60 * 60 * 1000)
          // text += '/' + parseInt(days) + '天'
        }
      }
      return text
    },
    toDelQuality(record) {
      if (record.platForm == '海澜') {
        return this.$messageWorkReport.warning('该质量通知单来源为[海澜],请前往海澜操作删除')
      }
      if (record.status == '1' || record.status == '2') {
        return this.$messageWorkReport.warning('质量通知单状态为审批中或审批通过，请勿删除')
      }
      if (!this.checkPermission(['WORK_REPORT_MANAGER'])) {
        if (record.crtUserId != this.userinfo.info.username) {
          return this.$messageWorkReport.warning('请勿删除非本人创建的质量通知单')
        }
      }
      let that = this
      Modal.confirm({
        title: '提醒',
        content: '是否确认删除质量通知单[' + record.qualityNo + ']',
        onOk() {
          postAction(that.urls.delQuality + '/' + record.id, {}).then((res) => {
            if (res.success) {
              that.$messageWorkReport.success('删除成功')
              that.fetchQualityList()
            } else {
              that.$messageWorkReport.error('删除失败')
            }
          })
        },
        onCancel() {},
      })
    },
    handleCancel() {
      this.$emit('hide')
    },
    pageChange(pageNo, pageSize) {
      this.$set(this.searchForm, 'pageSize', pageSize)
      this.$set(this.searchForm, 'pageNo', pageNo)
      this.fetchQualityList()
    },
    onShowSizeChange(current, pageSize) {
      this.searchForm.current = 1
      this.searchForm.pageSize = pageSize
      this.fetchQualityList()
    },
    handleToSearch() {
      this.searchForm.current = 1
      this.fetchQualityList()
    },
    handleToCancel() {
      this.showSearchForm = false
    },
    toMyTask() {},
    changeSave(index) {
      let quality = this.qualityRecords[index]
      postAction(this.urls.updateQuality, quality).then((res) => {
        if (res.success) {
          this.$messageWorkReport.success('更新[' + quality.qualityNo + ']成功')
          this.fetchQualityList()
        } else {
          this.$messageWorkReport.error('更新失败:' + res.message)
        }
      })
    },
    exportExcle() {
      let url = process.env.VUE_APP_API_BASE_URL + '/workReport/quality/export?1=1'
      this.handleExportXls('质量通知单列表', url, this.searchForm)
    },
    toEdit() {
      if (this.currentRecord) {
        if (this.currentRecord.platForm == '海澜') {
          let urlJump = this.$router.resolve({ path:'/workReport/quality/view/' + this.currentRecord.id + '/' + this.taskId })
          window.open(urlJump.href, '_blank')
        } else {
          let urlJump = this.$router.resolve({ path:'/workReport/editQuality/' + this.currentRecord.id })
          window.open(urlJump.href, '_blank')
        }
      }
    },
    toAdd() {
      let urlJump = this.$router.resolve({ path:'/workReport/addQuality' })
      window.open(urlJump.href, '_blank')
    },
  },
  watch: {
    loadList(newV, oldV) {
      if (newV) {
        this.$set(this.searchForm, 'current', 1)
        this.fetchQualityList()
      }
    },
  },
}
</script>
<style lang="less" scoped>
@import '~@assets/less/hte-main.less';
.page-main {
  .banner {
    background-image: url(~@assets/contract-top.png);
  }
  .container {
    .content-list {
      margin-top: 15px;
    }
  }
  .font-active {
    cursor: pointer;
  }
}
.contentStyle-default {
  display: block;
  width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.contentStyle-red {
  display: block;
  width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  color: red;
}
.contentStyle-yellow {
  display: block;
  width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  color: burlywood;
}
</style>